package com.example.yilu1;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.SearchView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.overlayutil.DrivingRouteOverlay;
import com.baidu.mapapi.overlayutil.WalkingRouteOverlay;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRouteLine;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteLine;
import com.baidu.mapapi.search.route.WalkingRoutePlanOption;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.baidu.mapapi.utils.DistanceUtil;
import com.baidu.mapapi.utils.route.BaiduMapRoutePlan;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MapActivity extends AppCompatActivity implements View.OnClickListener{
    public LocationClient mLocationClient;
    private MapView mapView;
    private BaiduMap baiduMap;
    private boolean is_FirstLocate,is_FirstPlan;
    private MyLocationData.Builder locationBuilder;
    private MyLocationData locationData;
    private EditText queryEdit;
    private ImageButton relocate_button,query_button;
    private RoutePlanSearch mSearch;
    private OnGetRoutePlanResultListener listener;
    private PlanNode stNode,enNode;
    private List<LatLng> wayPoints;
    private List<PlanNode>_goodLocations;
    private ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());//初始化mapView，注意要写在setContentView之前
        setContentView(R.layout.layout_map);

        ActionBar actionBar=getSupportActionBar();
        if(actionBar!=null) actionBar.hide();

        /*初始化LocationClient，注册监听器;   //使用的监听器是自己写的MyLocationListener*/
        mLocationClient=new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener((BDAbstractLocationListener) new MyLocationListener());
        /*初始化mapView*/
        mapView=(MapView) findViewById(R.id.mapView);
        /*初始化baiduMap，用于控制mapView*/
        baiduMap=mapView.getMap();
        baiduMap.setMyLocationEnabled(true);//使地图可以显示用户当前位置
        /*建立【【用户当前位置】的建造者】类对象*/
        locationBuilder=new MyLocationData.Builder();
        /*初始化路线规划检索实例*/     //监听器是自己写的MyOnGetRoutePlanResultListener
        mSearch= RoutePlanSearch.newInstance();
        listener=new MyOnGetRoutePlanResultListener();
        mSearch.setOnGetRoutePlanResultListener(listener);
        wayPoints=new ArrayList<>();
//        _goodLocations=PurchasingcarActivity.goodLocations;

        _goodLocations=new ArrayList<>();
       // _goodLocations.add(PlanNode.withCityNameAndPlaceName("济南",""));
        _goodLocations.add(PlanNode.withCityNameAndPlaceName("济南","安大城市广场"));
        //_goodLocations.add(PlanNode.withCityNameAndPlaceName("济南","济阳图书馆"));
        if(PurchasingcarActivity.goodLocations.size()>1)_goodLocations.add(PlanNode.withCityNameAndPlaceName("济南","华百广场"));
        //_goodLocations.add(PlanNode.withCityNameAndPlaceName("济南","安大美食广场"));
        if(PurchasingcarActivity.goodLocations.size()>2)_goodLocations.add(PlanNode.withCityNameAndPlaceName("济南","济阳银座购物广场"));

        PurchasingcarActivity.goodLocations.clear();
        //_goodLocations.add(new LatLng(117.182013,36.974136));
//        _goodLocations.add(new LatLng(117.17983,36.975973));
//        _goodLocations.add(new LatLng(117.179347,36.975934));
        progressBar=(ProgressBar)findViewById(R.id.progress_bar);


        /*其它变量的初始化*/
        is_FirstLocate=true; //
        is_FirstPlan=true;
        relocate_button=(ImageButton)findViewById(R.id.relocate_button);
        relocate_button.setOnClickListener(this);//
        queryEdit=(EditText)findViewById(R.id.queryEdit);
        query_button=(ImageButton)findViewById(R.id.query_button);
        query_button.setOnClickListener(this);


        /*申请权限*/
        List<String> permissionList=new ArrayList<>();
        if(ContextCompat.checkSelfPermission(MapActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED){
            permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if(ContextCompat.checkSelfPermission(MapActivity.this,Manifest.permission.READ_PHONE_STATE)
                        !=PackageManager.PERMISSION_GRANTED){
            permissionList.add(Manifest.permission.READ_PHONE_STATE);
        }
        if(ContextCompat.checkSelfPermission(MapActivity.this,Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        !=PackageManager.PERMISSION_GRANTED){
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if(!permissionList.isEmpty()){
            String [] permissions=permissionList.toArray(new String[permissionList.size()]);
            ActivityCompat.requestPermissions(MapActivity.this,permissions,1);
        }
        else {
            requestLocation();    //申请到权限之后调用此自定义函数
        }
    }//end of OnCreate()

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 1:
                if(grantResults.length>0){
                    for(int result:grantResults){
                        if(result!=PackageManager.PERMISSION_GRANTED){
                            Toast.makeText(MapActivity.this,"同意所有权限后才能使用本程序",Toast.LENGTH_SHORT).show();
                            finish();
                            return;
                        }
                    }
                    requestLocation();
                }
                else{
                    Toast.makeText(MapActivity.this,"发生未知错误",Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.stop();
        mapView.onDestroy();
        baiduMap.setMyLocationEnabled(false);
        mSearch.destroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.relocate_button:
                Log.d("touch:","relocate_button is touched");
                is_FirstLocate=true;
                requestLocation();
                break;
            case R.id.query_button:
                break;
            default:
                break;
        }
    }

    private class MyLocationListener extends BDAbstractLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {//重写该函数，描述获取到定位后的动作逻辑
            if(bdLocation.getLocType()==BDLocation.TypeGpsLocation
            ||bdLocation.getLocType()==BDLocation.TypeNetWorkLocation){
                navigateTo(bdLocation);
                Log.d("process:","after navigateTo bdLocation");
            }
        }
    }

    private class MyOnGetRoutePlanResultListener implements OnGetRoutePlanResultListener{

        @Override
        public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {
            List<WalkingRouteLine> routeLines = walkingRouteResult.getRouteLines();
            if (routeLines != null) {
                WalkingRouteLine routeLine=routeLines.get(0);
                List<WalkingRouteLine.WalkingStep> allStep = routeLine.getAllStep();
                for (WalkingRouteLine.WalkingStep walkingStep : allStep) {
                    if(is_FirstPlan){
                        wayPoints = walkingStep.getWayPoints();
                        is_FirstPlan=false;
                    }
                    else{
                        for(int i=1;i<walkingStep.getWayPoints().size();i++)
                            wayPoints.add(walkingStep.getWayPoints().get(i));
                    }
                }
            }
            else
                Toast.makeText(MapActivity.this,"路线规划出错了！",Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {

        }

        @Override
        public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {

        }

        @Override
        public void onGetDrivingRouteResult(DrivingRouteResult drivingRouteResult) {
            List<DrivingRouteLine> routeLines = drivingRouteResult.getRouteLines();
            if (routeLines != null) {
                DrivingRouteLine routeLine=routeLines.get(0);
                List<DrivingRouteLine.DrivingStep> allStep = routeLine.getAllStep();
                for (DrivingRouteLine.DrivingStep drivingStep : allStep) {
                    if(is_FirstPlan){
                        wayPoints = drivingStep.getWayPoints();
                        is_FirstPlan=false;
                    }
                    else{
                        for(int i=1;i<drivingStep.getWayPoints().size();i++)
                            wayPoints.add(drivingStep.getWayPoints().get(i));
                    }
                }
            }
            else
                Toast.makeText(MapActivity.this,"路线规划出错了！",Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {

        }

        @Override
        public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {

        }
    }

    private void requestLocation(){
        initLocation();
        mLocationClient.start();

    }
    private void initLocation(){
        LocationClientOption option=new LocationClientOption();
        option.setScanSpan(2000);
        option.setIsNeedAddress(true);
        mLocationClient.setLocOption(option);
    }
    private void navigateTo(BDLocation location){
        Log.d("process:","start navigateTo location");
        if(is_FirstLocate){     //首次定位时生成完整路线
            baiduMap.clear();

            LatLng ll=new LatLng(location.getLatitude(),location.getLongitude());
            MapStatusUpdate update= MapStatusUpdateFactory.newLatLng(ll);
            baiduMap.animateMapStatus(update);
            update=MapStatusUpdateFactory.zoomTo(18f);
            baiduMap.animateMapStatus(update);

            /**路线规划**/
            boolean flag=true;
            if(_goodLocations.isEmpty()){
                Toast.makeText(MapActivity.this,"尚未选择任何商品！",Toast.LENGTH_SHORT).show();
            }
            else{
                Log.d("lyc", "navigateTo: flag0");
                for(int i=0;i<_goodLocations.size();i++){
                    if(flag){
                        stNode=PlanNode.withLocation(ll);
                        //enNode=PlanNode.withLocation(_goodLocations.get(i));
                        enNode=_goodLocations.get(i);
                        flag=false;
                    }
                    else {
                        stNode=enNode;
                        //enNode=PlanNode.withLocation(_goodLocations.get(i));
                        enNode=_goodLocations.get(i);
                    }
                    if(DistanceUtil.getDistance(stNode.getLocation(),enNode.getLocation())>10000){
                        /**驾车路线规划**/
                        DrivingRoutePlanOption drivingRoutePlanOption = new DrivingRoutePlanOption();//参数设置类
                        drivingRoutePlanOption.from(stNode);//设置起点
                        drivingRoutePlanOption.to(enNode);//设置终点
                        /**路线规划策略，枚举类型：躲避拥堵、最短距离、较少费用、时间优先
                         * ECAR_TIME_FIRST：时间优先  *ECAR_AVOID_JAM：躲避拥堵
                         * ECAR_DIS_FIRST：最短距离   *ECAR_FEE_FIRST：较少费用**/
                        drivingRoutePlanOption.policy(DrivingRoutePlanOption.DrivingPolicy.ECAR_TIME_FIRST);
                        mSearch.drivingSearch(drivingRoutePlanOption);//查询
                    }
                    else{
                        WalkingRoutePlanOption walkingRoutePlanOption=new WalkingRoutePlanOption();
                        walkingRoutePlanOption.from(stNode);
                        walkingRoutePlanOption.to(enNode);
                        mSearch.walkingSearch(walkingRoutePlanOption);
                    }
                }
                _goodLocations.clear();
            }
            //enNode = PlanNode.withCityNameAndPlaceName("济南", "大明湖");//终点，PlanNode也支持输入坐标点
            is_FirstLocate=false;
        }
        locationBuilder.latitude(location.getLatitude());
        locationBuilder.longitude(location.getLongitude());
        locationData=locationBuilder.build();
        baiduMap.setMyLocationData(locationData);


        if (wayPoints.size() >= 2) {
            progressBar.setVisibility(View.VISIBLE);
            PolylineOptions polylineOptions = new PolylineOptions()
                    .color(0xFFFF8800)
                    .width(15);
            polylineOptions.points(wayPoints);
            baiduMap.addOverlay(polylineOptions);
            progressBar.setVisibility(View.INVISIBLE);
        }
    }
}
